package network.course6.bytebuf.tools;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import network.course6.bytebuf.model.Dog;

import java.io.UnsupportedEncodingException;

public class MsgEncoder extends MessageToByteEncoder<Dog> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Dog msg, ByteBuf out) throws Exception {
        //将对象转换为byte
        byte [] body = converToBytes(msg);
        System.out.println("Dog conver to bytes");
        if (body == null || body.length < 1){
            return;
        }
        //读取消息的长度
        int dataLength = body.length;
        //先将消息长度写入。也就是消息头
        out.writeInt(dataLength);
        //消息体中包含我们要发送的数据
        out.writeBytes(body);

    }

    private byte[] converToBytes(Dog dog) {
        if (dog == null){
            return null;
        }
        try {
        String contentString = JSON.toJSONString(dog);
       //字符串转换为byte数组
            return contentString.getBytes("ISO-8859-1");
        } catch (Exception e) {
            System.out.println("dog conver to bytes error");
            e.printStackTrace();
        }
        return null;
    }
}
